package com.quanyan.stadium.aop;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.stadium.component.cache.MyRedisTemplate;
import com.quanyan.stadium.component.cache.StadiumRedisConstants;
import com.quanyan.stadium.entity.TbGameEvent;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by xiaoxiao on 16/9/14.
 *
 * 对战表生成的时候利用aop逻辑来拆分业务
 */
//@Aspect
//@Configuration
public class GameRoundCreateAspect {


    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private OfficialGameCache officialGameCache;


    private static final Logger logger = LoggerFactory.getLogger(GameRoundCreateAspect.class);


    /**
     *
     * 监控轮次编排(对createGameRound方法进行切面)
     * */
    @Pointcut("execution(* com.quanyan.stadium.service.gameRules.AbsGameSystem.createGameRound(..))")
    public void createGameRound() {}


    /**
     *  对战表生成之前,一些简单的操作
     *
     * */
    @Before(value="createGameRound()")
    public void doBefore(JoinPoint jp) {

    }

    /**
     *  生成轮次后,一些简单的操作
     *
     * */
    @Around(value="createGameRound()")
    public Object doProcess(ProceedingJoinPoint point) throws Throwable {

        //初始化默认值
        Object retVal = null;

        //访问目标方法的参数：
        TbGameEvent tbGameEvent = new TbGameEvent();
        Object[] args = point.getArgs();
        if (args != null && args.length > 0 && args[0].getClass() == TbGameEvent.class) {
            tbGameEvent = (TbGameEvent) args[0];
        }
        if (null == tbGameEvent.getId()) {
            return retVal;
        }
        RedisKey redisKey = new RedisKey(RedisConstants.STADIUM_FAMILY_KEY, StadiumRedisConstants.getGameRoundGeneratingKey(tbGameEvent.getId()));
        long flag = myRedisTemplate.setnx(redisKey);
        if (flag == 0) {
            return redisKey;
        }

        //开启
        retVal = point.proceed();

        myRedisTemplate.delteKey(redisKey);
        return retVal;

    }

    /**
     *  轮次生成完成,触发相应的操作
     *
     *
     * */
    @AfterReturning(value="createGameRound()", returning = "rtv")
    public void doAfter(JoinPoint jp, Object rtv) throws Throwable{
        List<Integer> gameRoundIds = (List<Integer>) rtv;
        if (CollectionUtils.isNotEmpty(gameRoundIds)) {
            for (Integer temp : gameRoundIds) {
                officialGameCache.getGameRound(temp);
            }
        }
    }

    /**
     * 轮次生成失败,返回行管信息
     *
     * */



}
